import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/pages/event/OrderTypeEvent.dart';
import 'package:flutter_yres/pages/user/vip_order/order_list_entity.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/md5_sign.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:fluttertoast/fluttertoast.dart';

class AllOrderPage extends StatefulWidget {
  var type;
  AllOrderPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AllOrderView();
  }
}

class AllOrderView extends State<AllOrderPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  List<OrderListDataData> dataList = List();
  int page = 1;
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "";
  String order_type = "tb";
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
    APPLIC.eventBus.on<OrderEventTypeEvent>().listen((event) {
      order_type = event.user;
      page = 1;
      loadList();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    if ("tb" == order_type) {
      map['tk_status'] = widget.type == 0
          ? ""
          : widget.type == 1 ? "12" : widget.type == 2 ? "3" : "13";
    } else {
      map['order_status'] = widget.type == 0
          ? ""
          : widget.type == 1 ? "1" : widget.type == 2 ? "5" : "4";
    }
    map['type'] = 1;
    map['p'] = page;
    map['per'] = 10;
    Response<String> response = await HttpUtil().post(
        "tb" == order_type
            ? Api.BaseUrl + "/app.php?c=TaobaoOrder&a=getOrderList_new"
            : Api.BaseUrl + "/app.php?c=PddOrder&a=getOrderList",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    OrderListEntity homeListEntity = new OrderListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data);
        } else {
          dataList.addAll(homeListEntity.data);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.length == 0);
          if (homeListEntity.data.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Container(
      child: new Container(
        color: divideColor,
        child: new EasyRefresh(
          controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          child: ListView.separated(
              itemBuilder: order_type == "tb" ? _renderRow : _renderRow2,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 10,
                );
              },
              itemCount: dataList == null ? 0 : dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     order_id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    dataList[index].seller_shop_title,
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(35),
                        color: black),
                  ),
                ),
                Text(
                    dataList[index].tk_status == "3"
                        ? "已结算"
                        : dataList[index].tk_status == "12"
                            ? "已付款"
                            : dataList[index].tk_status == "13"
                                ? "已失效"
                                : "订单成功",
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(34),
                        color: Colors.red))
              ],
            ),
            Container(
              height: 10,
            ),
            Row(
              children: <Widget>[
                Image.network(
                  "http:" + dataList[index].goods_img,
                  width: 90,
                  height: 90,
                ),
                Container(
                  width: 5,
                ),
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      dataList[index].item_title,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(33),
                          color: black),
                    ),
                    Container(
                      height: 2,
                    ),
                    Text(
                      "订单号:" + dataList[index].trade_id,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(32),
                          color: Colors.black54),
                    ),
                    Container(
                      height: 1,
                    ),
                    Text(
                      "时间:" + dataList[index].create_time,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(30),
                          color: Colors.black54),
                    ),
                  ],
                ))
              ],
            ),
            Container(
              height: 7,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  "付款预估收入",
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(30),
                      color: Colors.black54),
                ),
                Container(
                  width: ScreenUtil.getInstance().setHeight(120)
                ),
                Text("付款金额",
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(30),
                        color: Colors.black54))
              ],
            ),
              Container(
              height: 3,
            ),
             Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  MONEY+dataList[index].commission,
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(36),
                      color: Colors.red),
                ),
                Container(
                  width: ScreenUtil.getInstance().setHeight(190)
                ),
                Text( MONEY+dataList[index].alipay_total_price,
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(36),
                        color: Colors.black87))
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _renderRow2(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     order_id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        child: Column(
          children: <Widget>[Text(dataList[index].seller_shop_title)],
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
